package com.web.admin.product;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.biz.ProductBizImpl;
import com.entity.Product;
import com.entity.UserInfo;

public class AddServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		//获取application应用程序对象application
		ServletContext application = this.getServletContext();
		//获取session会话对象session
		HttpSession session = request.getSession();
		//获取页面字符打印流对象out
		PrintWriter out = response.getWriter();
		
		Product p=new Product();
		//记录第几张图片为主导图片（封面）
		int iscover=0;
		//存储图片相对路径的集合
		List<String> imgs=new ArrayList<String>();
		//取得session中存放的登录者的id
		p.setUid(""+((UserInfo)session.getAttribute("loger")).getId());
		
		/**************处理上传表单的数据*****************/
		//创建FileItemFactory工厂对象
		FileItemFactory fif=new DiskFileItemFactory();
		//创建ServletFileUpload对象
		ServletFileUpload upload=new ServletFileUpload(fif);
		//设置上传文件的大小上限为1MB
		upload.setFileSizeMax(1024*1024*1);
		if(ServletFileUpload.isMultipartContent(request)){
			try{
				//解析request请求，并存储解析结果到list集合中
				List<FileItem> list = upload.parseRequest(request);
				//遍历集合
				for(FileItem item:list){
					//判断是否为上传域
					if(item.isFormField()){//不是上传域
						//获取表单的值且字符编码格式为utf—8
						String val=item.getString("utf-8");
						//获取表单的name的值
						String name=item.getFieldName();
						if(name.equals("pname"))	p.setPname(val);
						if(name.equals("price"))	p.setPrice(Double.parseDouble(val));
						if(name.equals("stock"))	p.setStock(Integer.parseInt(val));
						if(name.equals("comments"))	p.setComments(val);
						if(name.equals("kind"))		p.setKind(Integer.parseInt(val));
						if(name.equals("iscover"))	iscover=Integer.parseInt(val);
					}else{//是上传域
						//获取存放图片的images的绝对路径
						String path=application.getRealPath("images");
						//获取文件名
						String filename=new File(item.getName()).getName();
						//将图片的相对路径存放到imgs集合
						imgs.add("images/"+filename);
						//设置写入的绝对路径
						File savefile=new File(path+"/"+filename);
						try {
							//写入到服务器
							item.write(savefile);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
				//判断用户输入的设置封面的数字是否复合规范，不符合默认设置第一张为主导图片
				if(iscover<imgs.size() || iscover>imgs.size()){
					iscover=1;
				}
				//判断是否添加成功
				if(new ProductBizImpl().addPro(p, imgs, iscover)>0){
					out.print("<script>location='showPro.jsp';</script>");
				}else{
					out.print("<script>alert('添加失败');location='addPro.jsp';</script>");
				}
			} catch (FileSizeLimitExceededException e){//图片大小不合要求
				e.printStackTrace();
				out.print("<script>alert('图片大小需要小于1MB');history.back();</script>");
			} catch (FileUploadException e) {
				e.printStackTrace();
			}
		}else{
			out.print("<script>location='history.back()';</script>");
		}
		out.flush();
		out.close();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		doGet(request, response);
	}

}
